#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/11 14:09
# @Author  : JY.Liu
# @Site    : http://github.com/lh1993
# @Mail    : lhln0119@163.com
# @File    : sls_monitor.py
# @Software: PyCharm

import datetime
import asyncio
from tools.aliyun import AliyunSLS
from tools import get_config
from tools.logstore_monitor import exec_logstore_monitor


def main():
    print("#" * 50)
    sTime = datetime.datetime.now()
    now = datetime.datetime.now()
    before_5m = now - \
        datetime.timedelta(minutes=get_config.time_range)
    toTime = datetime.datetime.strftime(now, '%Y-%m-%d %H:%M:%S')
    fromTime = datetime.datetime.strftime(before_5m, '%Y-%m-%d %H:%M:%S')
    project = get_config.project
    query = get_config.query
    # 获取黑名单日志库列表
    black_logstore_list = get_config.black_logstore.split('|')
    print("黑名单日志库列表：%s" % black_logstore_list, flush=True)
    print("查询开始时间：%s" % fromTime, flush=True)
    print("查询结束时间：%s" % toTime, flush=True)
    print("查询语句：%s" % query, flush=True)
    ali = AliyunSLS()
    logstores_list = ali.getListLogstores()
    # 协程调用
    tasks = []
    for logstore in logstores_list:
        tasks.append(
            asyncio.ensure_future(
                exec_logstore_monitor(
                    project=project,
                    logstore=logstore,
                    query=query,
                    fromTime=fromTime,
                    toTime=toTime)))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    print("#" * 50)
    for task in tasks:
        try:
            print('Task Result:', task.result(), flush=True)
        except Exception as e:
            print("异常：%s" % e, flush=True)
    eTime = datetime.datetime.now()
    print("程序开始时间：%s" % sTime, flush=True)
    print("程序结束时间：%s" % eTime, flush=True)


if __name__ == '__main__':
    main()
